<template>
  <div class="p-6 space-y-4">
    <!-- 搜索区域 -->
    <el-card shadow="never" class="rounded-lg">
      <el-form :model="filters" label-position="top" class="search-form" @keyup.enter.native="onSearch">
        <el-row :gutter="12" align="bottom">
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="装置编号">
              <el-input v-model="filters.sczzbh" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="装置名称">
              <el-input v-model="filters.sczzmc" clearable placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="5">
            <el-form-item label="所属部门">
              <el-cascader
                v-model="filters.createDept"
                :options="departmentTreeOptions"
                :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'bmmc' }"
                :show-all-levels="false"
                clearable
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :lg="9" class="flex justify-end items-end gap-2">
            <el-button type="primary" :loading="queryLoading" @click="onSearch">
              <el-icon class="mr-1">
                <Search />
              </el-icon>
              查询
            </el-button>
            <el-button :icon="Plus" @click="onCreate()">新增</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 结果表格 -->
    <el-card shadow="never" class="rounded-lg">
      <div v-loading="tableLoading">
        <el-table :data="tableData" border>
          <el-table-column label="序号" type="index" width="80" align="center" :index="indexMethod" />
          <el-table-column label="装置编号" prop="sczzbh" min-width="120" />
          <el-table-column label="装置名称" prop="sczzmc" min-width="160" />
          <el-table-column label="装置用途" prop="zzyt" min-width="180" />
          <el-table-column label="关联设备数量" prop="equipmentCount" width="140" align="center" />
          <el-table-column label="装置投用时间" prop="tysj" min-width="140" />
          <el-table-column label="装置状态" width="120" align="center">
            <template #default="scope">
              <el-tag :type="statusTagType(scope.row.zzzt)">{{ equipmentStatusKeyName[scope.row.zzzt] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="所属部门" prop="createDeptName" min-width="140" />
          <el-table-column label="负责人" prop="fzr" min-width="120" />
          <el-table-column label="操作" width="160" align="center">
            <template #default="scope">
              <div class="flex justify-center items-center gap-2">
                <el-button link type="primary" :icon="View" @click="onView(scope.row)">详情</el-button>
                <el-button link type="danger" @click="onDelete(scope.row)">删除</el-button>
              </div>
            </template>
          </el-table-column>
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
      </div>
      <div class="flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" :width="formOperationType === FormOperationTypeEnum.ADD ? '800' : '70%'" destroy-on-close>
      <template #header>
        <div class="flex items-center justify-between pr-10">
          <div class="flex items-center gap-2">
            <div class="w-1 h-6 bg-#5B8FF9" />
            <div class="text-lg font-600">
              <template v-if="formOperationType === FormOperationTypeEnum.ADD"> 新增装置 </template>
              <template v-else>
                {{ detailTitle }}
              </template>
            </div>
          </div>
          <div>
            <el-button v-if="formOperationType !== FormOperationTypeEnum.ADD" type="primary" @click="onEdit">
              <svg-icon icon-class="edit-1"></svg-icon>
              编辑
            </el-button>
          </div>
        </div>
      </template>
      <el-form ref="formRef" :model="detailRecord" :rules="formRules" label-position="left" label-width="110px" class="w-full">
        <el-row :gutter="16">
          <el-col :xs="24" :md="12">
            <el-form-item label="装置编号" prop="sczzbh">
              <span v-if="viewForm">{{ detailRecord?.sczzbh || '-' }}</span>
              <el-input v-else v-model="detailRecord.sczzbh" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="装置名称" prop="sczzmc">
              <span v-if="viewForm">{{ detailRecord?.sczzmc || '-' }}</span>
              <el-input v-else v-model="detailRecord.sczzmc" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="装置状态" prop="zzzt">
              <span v-if="viewForm">{{ detailRecord?.zzzt || '-' }}</span>
              <el-select v-else v-model="detailRecord.zzzt" placeholder="请选择" clearable>
                <el-option v-for="(item, index) in equipmentStatusOptions" :key="index" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="所属部门" prop="createDept">
              <span v-if="viewForm">{{ detailRecord?.createDeptName || '-' }}</span>
              <el-cascader
                v-else
                v-model="detailRecord.createDept"
                :options="departmentTreeOptions"
                :props="{ checkStrictly: true, emitPath: false, value: 'id', label: 'bmmc' }"
                :show-all-levels="false"
                clearable
                style="width: 100%"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="装置投用时间" prop="tysj">
              <span v-if="viewForm">{{ detailRecord?.tysj || '-' }}</span>
              <el-date-picker
                v-else
                clearable
                v-model="detailRecord.tysj"
                style="width: 100%"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择"
              />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="负责人" prop="fzr">
              <span v-if="viewForm">{{ detailRecord?.fzr || '-' }}</span>
              <el-input v-else v-model="detailRecord.fzr" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24" :md="12">
            <el-form-item label="联系方式" prop="lxfs">
              <span v-if="viewForm">{{ detailRecord?.lxfs || '-' }}</span>
              <el-input v-else v-model="detailRecord.lxfs" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
          <el-col :xs="24">
            <el-form-item label="装置用途" prop="zzyt">
              <span v-if="viewForm">{{ detailRecord?.zzyt || '-' }}</span>
              <el-input v-else type="textarea" v-model="detailRecord.zzyt" placeholder="请输入" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-if="formOperationType !== FormOperationTypeEnum.ADD">
        <div class="flex justify-between items-center mb-2 mt-2">
          <div class="font-600">关联设备</div>
          <!--        <el-button type="primary" size="small" @click="associateVisible = true">关联设备</el-button>-->
        </div>
        <el-table :data="detailEquipTable" border>
          <el-table-column label="序号" type="index" width="70" align="center" />
          <el-table-column label="设备位号" prop="sbwh" min-width="120" />
          <el-table-column label="设备名称" prop="sbmc" min-width="140" />
          <el-table-column label="设备类型" prop="sblx" min-width="140" />
          <el-table-column label="特种设备分类" prop="tzsbfl" min-width="140" />
          <el-table-column label="安全附件类型" prop="aqfjfl" min-width="140" />
          <el-table-column label="设备等级" prop="sbdj" min-width="120" />
          <el-table-column label="所属部门" prop="createDeptName" min-width="120" />
          <el-table-column label="状态" width="110" align="center">
            <template #default="scope">
              <el-tag :type="statusTagType(scope.row.sbzt)">{{ equipmentStatusKeyName[scope.row.sbzt] || '-' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="安装位置" prop="azwz" min-width="160" />
          <!--        <el-table-column label="操作" width="120" align="center">-->
          <!--          <template #default>—</template>-->
          <!--        </el-table-column>-->
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
      </div>

      <!-- 内嵌弹窗：关联设备 -->
      <el-dialog v-model="associateVisible" title="关联设备" width="760px" append-to-body>
        <el-form :model="associateFilters" label-position="top" class="search-form">
          <el-row :gutter="12" align="bottom">
            <el-col :xs="24" :sm="12" :lg="8">
              <el-form-item label="设备名称">
                <el-input v-model="associateFilters.name" clearable placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="8">
              <el-form-item label="设备位号">
                <el-input v-model="associateFilters.code" clearable placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :lg="8">
              <el-form-item label="所属部门">
                <el-select v-model="associateFilters.department" clearable placeholder="请选择">
                  <el-option v-for="d in departmentOptions" :key="d" :label="d" :value="d" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-table :data="associateTable" border class="mt-2">
          <el-table-column label="序号" type="index" width="70" align="center" />
          <el-table-column label="设备名称" prop="name" min-width="140" />
          <el-table-column label="设备位号" prop="code" min-width="120" />
          <el-table-column label="所属部门" prop="department" min-width="120" />
          <template #empty>
            <el-empty description="暂无数据" />
          </template>
        </el-table>
        <template #footer>
          <el-button @click="associateVisible = false">关闭</el-button>
          <el-button type="primary" @click="associateVisible = false">确定</el-button>
        </template>
      </el-dialog>

      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="detailVisible = false">
            <el-icon class="mr-1">
              <Close />
            </el-icon>
            关闭
          </el-button>
          <el-button type="primary" @click="onSave" v-if="formOperationType !== FormOperationTypeEnum.INFO">
            <el-icon class="mr-1">
              <Check />
            </el-icon>
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { Check, Close, Plus, Search, View } from '@element-plus/icons-vue';
import { DeviceForm, DeviceQuery, DeviceVO } from '@/api/system/device/types';
import { addDevice, delDevice, listDevice, updateDevice } from '@/api/system/device';
import { EquipmentVO, equipmentStatusKeyName, equipmentStatusMap, getOptionsByKeyMap } from '@/api/system/equipment/types';
import { FormOperationTypeEnum } from '@/enums';
import { listDepartmentTree } from '@/api/system/department';
import { DepartmentTree } from '@/api/system/department/types';

const formOperationType = ref(FormOperationTypeEnum.ADD);

const viewForm = computed(() => formOperationType.value === FormOperationTypeEnum.INFO);

const filters = reactive({ sczzbh: '', sczzmc: '', createDept: '' });
const departmentOptions = ['生产部门', '设备部', '安环部', '工艺部'];

const queryLoading = ref(false);
const tableLoading = ref(false);

const pagination = reactive({ currentPage: 1, pageSize: 10, total: 0 });
const tableData = ref<DeviceVO[]>([]);

const statusTagType = (s: string) => equipmentStatusMap[s] ?? 'info';

const indexMethod = (index: number) => (pagination.currentPage - 1) * pagination.pageSize + index + 1;

const fetchList = async () => {
  tableLoading.value = true;
  queryLoading.value = true;
  try {
    const params: DeviceQuery = {
      ...filters,
      pageSize: pagination.pageSize,
      pageNum: pagination.currentPage
    };
    listDevice(params)
      .then((res) => {
        if (res.rows && res.rows?.length > 0) {
          tableData.value = res.rows;
          pagination.total = res?.total;
        } else {
          tableData.value = [];
        }
      })
      .catch((e) => {
        tableData.value = [];
        console.error(e);
      })
      .finally(() => {
        queryLoading.value = false;
        tableLoading.value = false;
      });
  } catch (e) {
    ElMessage.error('数据加载失败，请稍后重试');
  } finally {
    tableLoading.value = false;
    queryLoading.value = false;
  }
};

const onSearch = () => {
  pagination.currentPage = 1;
  fetchList();
};
const onSizeChange = (s: number) => {
  pagination.pageSize = s;
  pagination.currentPage = 1;
  fetchList();
};
const onPageChange = (p: number) => {
  pagination.currentPage = p;
  fetchList();
};

interface DeviceFormInfo extends DeviceForm {
  createDeptName: string;
  equipmentList: EquipmentVO[];
}

const baseForm: DeviceFormInfo = {
  id: undefined,
  /** 生产装置名称（必填）*/
  sczzmc: undefined,
  /** 生产装置编号（必填）*/
  sczzbh: undefined,
  /** 投用时间（必填）*/
  tysj: undefined,
  /** 负责人（必填）*/
  fzr: undefined,
  /** 联系方式（必填）*/
  lxfs: undefined,
  /** 装置用途（必填）*/
  zzyt: undefined,
  /** 装置状态：0停用，1启用（必填）*/
  zzzt: undefined,
  /** 所属部门（必填）*/
  createDept: undefined,
  /** 所属部门（必填）*/
  createDeptName: undefined,
  /** 所属部门（必填）*/
  equipmentList: undefined
};
const formRef = ref<FormInstance>();
const detailVisible = ref(false);
const detailTitle = ref('装置详情');
const detailRecord = ref<DeviceFormInfo | null>({ ...baseForm });
const detailEquipTable = ref<EquipmentVO[]>([]);

const associateVisible = ref(false);
const associateFilters = reactive({ name: '', code: '', department: '' });
const associateTable = ref<Pick<EquipmentVO, 'name' | 'code' | 'department'>[]>([]);

interface RuleForm {
  sczzbh: string;
  sczzmc: string;
  createDept: string;
  tysj: string;
  zzzt: string;
  fzr: string;
  lxfs: string;
  zzyt: string;
}
const formRules = reactive<FormRules<RuleForm>>({
  sczzbh: [{ required: true, message: '请输入', trigger: 'blur' }],
  sczzmc: [{ required: true, message: '请输入', trigger: 'blur' }],
  createDept: [{ required: true, message: '请选择', trigger: 'change' }],
  tysj: [{ required: true, message: '请选择', trigger: 'change' }],
  zzzt: [{ required: true, message: '请选择', trigger: 'change' }],
  fzr: [{ required: true, message: '请输入', trigger: 'blur' }],
  lxfs: [{ required: true, message: '请输入', trigger: 'blur' }],
  zzyt: [{ required: true, message: '请输入', trigger: 'blur' }]
});

const onCreate = () => {
  formOperationType.value = FormOperationTypeEnum.ADD;
  restForm();
  detailVisible.value = true;
};

const onEdit = () => {
  formOperationType.value = FormOperationTypeEnum.EDIT;
};
const restForm = () => {
  detailRecord.value = { ...baseForm };
};
const onView = (row: DeviceFormInfo) => {
  formOperationType.value = FormOperationTypeEnum.INFO;
  restForm();
  detailRecord.value = { ...row };
  detailTitle.value = `${row.sczzmc}（${row.sczzbh}）`;
  detailEquipTable.value = row.equipmentList;
  // mock associate list
  // associateTable.value = [
  //   { name: '备用反应釜', code: 'VO102A', department: row.department },
  //   { name: '换热器', code: 'HT450', department: row.department },
  //   { name: '安全阀', code: 'SA600', department: row.department }
  // ];
  detailVisible.value = true;
};

const onSave = () => {
  formRef.value.validate((valid, _fields) => {
    if (valid) {
      if (formOperationType.value === FormOperationTypeEnum.EDIT && detailRecord.value?.id) {
        updateDevice(detailRecord.value)
          .then((_res) => {
            ElMessage.success('保存成功');
            detailVisible.value = false;
          })
          .catch((e) => {
            console.error(e);
          })
          .finally(() => {
            fetchList();
          });
      } else {
        addDevice(detailRecord.value)
          .then((_res) => {
            ElMessage.success('保存成功');
            detailVisible.value = false;
          })
          .catch((e) => {
            console.error(e);
          })
          .finally(() => {
            fetchList();
          });
      }
    }
  });
};

const onDelete = async (row: DeviceFormInfo) => {
  try {
    await ElMessageBox.confirm(`确认删除“${row.sczzmc}（${row.sczzbh}）”？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    tableLoading.value = true;
    await delDevice(row.id);
    ElMessage.success('删除成功');
    await fetchList();
  } catch (e: any) {
    if (e !== 'cancel' && e !== 'close') ElMessage.error('删除失败，请稍后重试');
  } finally {
    tableLoading.value = false;
  }
};

const equipmentStatusOptions = getOptionsByKeyMap(equipmentStatusKeyName);
const departmentTreeOptions = ref<DepartmentTree[]>([]);

const getDepartmentTree = async () => {
  const res = await listDepartmentTree();
  if (res.data && res.data.length > 0) {
    departmentTreeOptions.value = res.data;
  } else {
    departmentTreeOptions.value = [];
  }
};

onMounted(async () => {
  await getDepartmentTree();
  await fetchList();
});
</script>
